<?php

namespace app\api\controller;
use app\admin\model\Admin;
use app\api\model\SaleModel;
use app\api\model\SaleRelation;
use app\api\model\PrepareModel;
use app\api\model\PurchaseModel;
use app\api\model\ProductionModel;
use app\api\model\ProductStock;
use app\api\model\Product;
use app\api\model\UserModel;
use app\api\model\Commodity;
use app\api\model\SupplierModel;
use think\Request;
use app\api\model\SaleReturn;
use app\api\model\SetAccountFlow;
use app\api\model\ArrayPaginate;
use app\api\model\StoreModel;
class Index extends Common
{
    use ArrayPaginate;
   private const cache_time = 1;
    /**
     * 首页
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        //待处理单据
        $l = 0;
        $list['sale_put'] =SaleModel::where('status',5)->count();
        $list['prepare_put'] =PrepareModel::where('status',5)->count();
        $list['purchase_put'] =PurchaseModel::where('status',1)->count();
        $list['production_put'] =ProductionModel::where('status',4)->count();
        //库存预警
        $current = ProductStock::cache(self::cache_time)->select();
        $product = Product::cache(self::cache_time)->select();
        $upper = [];
        $lower = [];
        foreach ($product as $k=>$v){
            foreach ($current as $k1=>$v1){
                if($v['stock_warning'] == 0){
                    if($v1['stock'] >= $v['stock_upper']){
                        $upper[] = true;
                    }
                    if($v1['stock'] <= $v['stock_lower']){
                        $lower[] = true;
                    }
                }
            }
        }
        $list['stock_upper'] = count($upper);
        $list['stock_lower'] = count($lower);
        //今天销售统计
        $today_start_time =date("Y-m-d H:i:s", mktime(0, 0, 0, date('m'), date('d'), date('Y')));
        $today_end_time = date("Y-m-d H:i:s", mktime(0, 0, 0, date('m'), date('d')+1, date('Y'))-1);
        $today_start_time =strtotime($today_start_time);
        $today_end_time =strtotime($today_end_time);
        $where[] = ['create_time','between',[$today_start_time,$today_end_time]];
        $where[] = ['status','=',4];
        $todaySale = SaleModel::where($where)->field('id,payment')->cache(self::cache_time)->select();
        // var_dump($todaySale);exit();
        $sale_id =[];
        $sale_money =[];
        foreach($todaySale as $k=>$v){
            $sale_id[] =$v['id'];
            $sale_money[] =$v['payment'];
        }
        $list['today_sale_num'] = count($sale_id);
        $list['today_sale_money'] = array_sum($sale_money);
        //昨天销售统计
        $yesterday_start = strtotime(date("Y-m-d",strtotime("-1 day")));   //昨天开始时间
        $yesterday_end = $yesterday_start+24 * 60 * 60-1;  //昨天结束时间
        $yesterday[] = ['create_time','between',[$yesterday_start,$yesterday_end]];
        $yesterday[] = ['status','=',4];
        $yesterdaySale = SaleModel::where($yesterday)->field('id,payment')->cache(self::cache_time)->select();
        $yesterday_id = [];
        $yesterday_money = [];
        foreach($yesterdaySale as $k=>$v){
            $yesterday_id[] = $v['id'];
            $yesterday_money[] = $v['payment'];
        }
        $list['yesterday_sale_num'] = count($yesterday_id);
        $list['yesterday_sale_money'] = array_sum($yesterday_money);
        //今天采购统计
        $todayPurchase = PurchaseModel::where($where)->field('id,payment')->cache(self::cache_time)->select();
        $today_purchase_id = [];
        $today_purchase_money = [];
        foreach($todayPurchase as $k=>$v){
            $today_purchase_id[] = $v['id'];
            $today_purchase_money[] = $v['payment'];
        }
        $list['today_purchase_num'] = count($today_purchase_id);
        $list['today_purchase_money'] = array_sum($today_purchase_money);
        //昨天采购统计
        $yesterdayPurchase = PurchaseModel::where($yesterday)->field('id,payment')->cache(self::cache_time)->select();
        $yesterday_purchase_id = [];
        $yesterday_purchase_money = [];
        foreach($yesterdayPurchase as $k=>$v){
            $yesterday_purchase_id[] = $v['id'];
            $yesterday_purchase_money[] = $v['payment'];
        }
        $list['yesterday_purchase_num'] = count($yesterday_purchase_id);
        $list['yesterday_purchase_money'] = array_sum($yesterday_purchase_money);
        // 账户余额
        $list['money'] = \app\api\model\SetAccount::sum('money');
        //应收客户款
        $list['total'] = UserModel::sum('arrears');
        //应付供应商款
        $list['pay'] = SupplierModel::sum('arrear');
        //库存总数
        $list['stock'] = ProductStock::sum('stock');
        //库存总成本
        $stock = ProductStock::select();
        $cost = [];
        foreach($stock as $k=>$v){
            $purchase_price = Commodity::where('id',$v['commodity_id'])->value('purchase_price');
            $cost[] = $v['stock'] * $purchase_price;
        }
        $list['cost'] = array_sum($cost);
        return $this->returnJson(200,'success',$list);
    }

    /**
     * 经营概况 ----- 销售汇总
     */
    public function SaleSummary(Request $request)
    {
        $type = $request->param('type');
        $upper = $request->param('num');
        if($type == 'date'){
            if($upper > 0) {
                //后一天
                $start_time = mktime(0,0,0,date('m'),date('d')+$upper,date('Y'));
                $end_time = mktime(0,0,0,date('m'),date('d')+$upper+1,date('Y'))-1;
            }else if($upper < 0){
                //前一天
                $start_time = mktime(0,0,0,date('m'),date('d')+$upper,date('Y'));
                $end_time = mktime(0,0,0,date('m'),date('d')-1,date('Y'))-1;
            }else{
                //当天
                $start_time = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $end_time = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
            }
            $list['start_time'] = date('Y-m-d',$start_time);
            $list['end_time'] = date('Y-m-d',$end_time);
            //前一天 现金条件
            $xian_yes = [
                ['payment_mode','=','现金'],
                ['business_time','between',[strtotime(" -1 day", $start_time),strtotime(" -1 day", $end_time)]],
                ['business_type','=','销售单']
            ];
            //前一天或后一天 微信条件
            $weChat_yes = [
                ['payment_mode','=','微信'],
                ['business_time','between',[strtotime(" -1 day", $start_time),strtotime(" -1 day", $end_time)]],
                ['business_type','=','销售单']
            ];
            //前一天或后一天 支付宝条件
            $ali_yes = [
                ['payment_mode','=','支付宝'],
                ['business_time','between',[strtotime(" -1 day", $start_time),strtotime(" -1 day", $end_time)]],
                ['business_type','=','销售单']
            ];
            //前一天或后一天 银行卡条件
            $blank_yes = [
                ['payment_mode','=','银行卡'],
                ['business_time','between',[strtotime(" -1 day", $start_time),strtotime(" -1 day", $end_time)]],
                ['business_type','=','销售单']
            ];
            //前一天或后一天 总金额、总单数 百分比条件
            $yesterday[] = ['create_time','between',[strtotime(" -1 day", $start_time),strtotime(" -1 day", $end_time)]];
        }else if($type == 'week'){
            if($upper > 0) {//下周
                $start_time = mktime(0, 0 , 0,date("m"),date("d")-date("w")+1+7*$upper,date("Y"));
                $end_time = mktime(23,59,59,date("m"),date("d")-date("w")+7+7*$upper,date("Y"));
            }else if($upper < 0){//上周
                $start_time = mktime(0, 0 , 0,date("m"),date("d")-date("w")+1+7*$upper,date("Y"));
                $end_time = mktime(23,59,59,date("m"),date("d")-date("w")+7+7*$upper,date("Y"));
            }else{//本周
                $start_time = mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"));
                $end_time = mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"));
            }
            $list['start_time'] = date('Y-m-d',$start_time);
            $list['end_time'] = date('Y-m-d',$end_time);
            //前一周 现金条件
            $xian_yes = [
                ['payment_mode','=','现金'],
                ['business_time','between',[strtotime(" -1 week", $start_time),strtotime(" -1 week", $end_time)]],
                ['business_type','=','销售单']
            ];
            //前一周或后一周 微信条件
            $weChat_yes = [
                ['payment_mode','=','微信'],
                ['business_time','between',[strtotime(" -1 week", $start_time),strtotime(" -1 week", $end_time)]],
                ['business_type','=','销售单']
            ];
            //上周或下周 支付宝条件
            $ali_yes = [
                ['payment_mode','=','支付宝'],
                ['business_time','between',[strtotime(" -1 week", $start_time),strtotime(" -1 week", $end_time)]],
                ['business_type','=','销售单']
            ];
            //上周或下周 银行卡条件
            $blank_yes = [
                ['payment_mode','=','银行卡'],
                ['business_time','between',[strtotime(" -1 week", $start_time),strtotime(" -1 week", $end_time)]],
                ['business_type','=','销售单']
            ];
            //上周或下周总金额、总单数 百分比条件
            $yesterday[] = ['create_time','between',[strtotime(" -1 week", $start_time),strtotime(" -1 week", $end_time)]];
        }else if($type == 'month'){
            if($upper > 0) {//下月
                $start_time = mktime(0, 0 , 0,date("m")+$upper,1,date("Y"));
                $end_time = mktime(23,59,59,date("m")+$upper+1 ,0,date("Y"));
            }else if($upper < 0){//上月
                $start_time = mktime(0, 0 , 0,date("m")+$upper-1,1,date("Y"));
                $end_time = mktime(23,59,59,date("m")+$upper ,0,date("Y"));
            }else{//本月
                $start_time = mktime(0, 0 , 0,date("m"),1,date("Y"));
                $end_time = mktime(23,59,59,date("m"),date("t"),date("Y"));
            }
            $list['start_time'] = date('Y-m-d',$start_time);
            $list['end_time'] = date('Y-m-d',$end_time);
            //上月 现金条件
            $xian_yes = [
                ['payment_mode','=','现金'],
                ['business_time','between',[strtotime(" $upper month", $start_time),$end_time - date('t',$end_time) *(24 * 60 * 60)]],
                ['business_type','=','销售单']
            ];
            //前一月或后一月 微信条件
            $weChat_yes = [
                ['payment_mode','=','微信'],
                ['business_time','between',[strtotime(" -1 month", $start_time),strtotime(" -1 month", $end_time)]],
                ['business_type','=','销售单']
            ];
            //上月或下月 支付宝条件
            $ali_yes = [
                ['payment_mode','=','支付宝'],
                ['business_time','between',[strtotime(" -1 month", $start_time),strtotime(" -1 month", $end_time)]],
                ['business_type','=','销售单']
            ];
            //上月或下月 银行卡条件
            $blank_yes = [
                ['payment_mode','=','银行卡'],
                ['business_time','between',[strtotime(" -1 month", $start_time),strtotime(" -1 month", $end_time)]],
                ['business_type','=','销售单']
            ];
            //上月或下月总金额、总单数 百分比条件
            $yesterday[] = ['create_time','between',[strtotime(" -1 month", $start_time),strtotime(" -1 month", $end_time)]];
        }else if($type == 'year'){
            if($upper > 0) {//明年
                $start_time = mktime(0, 0 , 0,1,1,date("Y")+$upper);
                $end_time = mktime(23, 59, 59, 12, 31, date('Y')+$upper);
            }else if ($upper < 0){//去年
                $start_time = mktime(0, 0 , 0,1,1,date("Y")+$upper);
                $end_time = mktime(23, 59, 59, 12, 31, date('Y')+$upper);
            }else{//今年
                $start_time = mktime(0, 0 , 0,1,1,date("Y"));
                $end_time = mktime(23, 59, 59, 12, 31, date('Y'));
            }
            $list['start_time'] = date('Y-m-d',$start_time);
            $list['end_time'] = date('Y-m-d',$end_time);
            //去年 现金条件
            $xian_yes = [
                ['payment_mode','=','现金'],
                ['business_time','between',[strtotime(" -1 year", $start_time),strtotime(" -1 year", $end_time)]],
                ['business_type','=','销售单']
            ];
            //去年或明年 微信条件
            $weChat_yes = [
                ['payment_mode','=','微信'],
                ['business_time','between',[strtotime(" -1 year", $start_time),strtotime(" -1 year", $end_time)]],
                ['business_type','=','销售单']
            ];
            //去年或明年 支付宝条件
            $ali_yes = [
                ['payment_mode','=','支付宝'],
                ['business_time','between',[strtotime(" -1 year", $start_time),strtotime(" -1 year", $end_time)]],
                ['business_type','=','销售单']
            ];
            //去年或明年 银行卡条件
            $blank_yes = [
                ['payment_mode','=','银行卡'],
                ['business_time','between',[strtotime(" -1 year", $start_time),strtotime(" -1 year", $end_time)]],
                ['business_type','=','销售单']
            ];
            //去年或明年总金额、总单数 百分比条件
            $yesterday[] = ['create_time','between',[strtotime(" -1 year", $start_time),strtotime(" -1 year", $end_time)]];
        }
        //销售条件
        $where[] = ['create_time','between',[$start_time,$end_time]];
        $where[] = ['status','=',4];
        $todaySale = SaleModel::where($where)->field('id,payment')->cache(self::cache_time)->select();
        $sale_id =[];
        $sale_money =[];
        foreach($todaySale as $k=>$v){
            $sale_id[] =$v['id'];
            $sale_money[] =$v['payment'];
        }
        $list['sale_num'] = count($sale_id);
        $list['sale_money'] = array_sum($sale_money);
        //退货条件
        $where1[] = ['create_time','between',[$start_time,$end_time]];
        $where1[] = ['status','=',1];
        $saleReturn = SaleReturn::where($where1)->field('id,payment')->cache(self::cache_time)->select();
        $return_id =[];
        $return_money =[];
        foreach($saleReturn as $k=>$v){
            $return_id[] =$v['id'];
            $return_money[] =$v['payment'];
        }
        $list['return_num'] = count($return_id);
        $list['return_money'] = array_sum($return_money);
        //现金条件
        $xian = [
            ['payment_mode','=','现金'],
            ['business_time','between',[$start_time,$end_time]],
            ['business_type','=','销售单']
        ];
        $list['xian']['xian_num'] = SetAccountFlow::where($xian)->count();
        $list['xian']['xian_money'] = array_sum(SetAccountFlow::where($xian)->column('in_amount'));
        $arr1_xian = SetAccountFlow::where($xian_yes)->count();
        $r_xian1 = $this->yunsuan($list['xian']['xian_num'],$arr1_xian);
        $list['xian']['xian_num'] = empty($list['xian']['xian_num']) ? ['xian_num' => 0] : ['xian_num' => $list['xian']['xian_num']];
        if($r_xian1 >= 0){
            $list['xian']['xian_num']['bill_num'] = $r_xian1;
            $list['xian']['xian_num']['lower'] = true;
        }else{
            $list['xian']['xian_num']['bill_num'] = abs($r_xian1);
            $list['xian']['xian_num']['lower'] = false;
        }
        $arr2_xian = array_sum(SetAccountFlow::where($xian_yes)->column('in_amount'));
        $r_xian2 = $this->yunsuan($list['xian']['xian_money'],$arr2_xian);
        $list['xian']['xian_money'] = empty($list['xian']['xian_money']) ? ['xian_money' => 0] : ['xian_money' => $list['xian']['xian_money']];
        if($r_xian2 >= 0){
            $list['xian']['xian_money']['bill_money'] = $r_xian2;
            $list['xian']['xian_money']['lower'] = true;
        }else{
            $list['xian']['xian_money']['bill_money'] = abs($r_xian2);
            $list['xian']['xian_money']['lower'] = false;
        }
        //微信条件
        $weChat = [
            ['payment_mode','=','微信'],
            ['business_time','between',[$start_time,$end_time]],
            ['business_type','=','销售单']
        ];
        $list['weChat']['weChat_num'] = SetAccountFlow::where($weChat)->count();
        $list['weChat']['weChat_money'] = array_sum(SetAccountFlow::where($weChat)->column('in_amount'));
        $arr1_wei = SetAccountFlow::where($weChat_yes)->count();
        $r_wei1 = $this->yunsuan($list['weChat']['weChat_num'],$arr1_wei);
        $list['weChat']['weChat_num'] = empty($list['weChat']['weChat_num']) ? ['weChat_num' => 0] : ['weChat_num' => $list['weChat']['weChat_num']];
        if($r_wei1 >= 0){
            $list['weChat']['weChat_num']['bill_num'] = $r_wei1;
            $list['weChat']['weChat_num']['lower'] = true;
        }else{
            $list['weChat']['weChat_num']['bill_num'] = abs($r_wei1);
            $list['weChat']['weChat_num']['lower'] = false;
        }
        $arr2_wei = array_sum(SetAccountFlow::where($weChat_yes)->column('in_amount'));
        $r_wei2 = $this->yunsuan($list['weChat']['weChat_money'],$arr2_wei);
        $list['weChat']['weChat_money'] = empty($list['weChat']['weChat_money']) ? ['weChat_money' => 0] : ['weChat_money' =>$list['weChat']['weChat_money']];
        if($r_wei2 >= 0){
            $list['weChat']['weChat_money']['bill_money'] = $r_wei2;
            $list['weChat']['weChat_money']['lower'] = true;
        }else{
            $list['weChat']['weChat_money']['bill_money'] = abs($r_wei2);
            $list['weChat']['weChat_money']['lower'] = false;
        }
        //支付宝 条件
        $ali = [
            ['payment_mode','=','支付宝'],
            ['business_time','between',[$start_time,$end_time]],
            ['business_type','=','销售单']
        ];
        $list['ali']['ali_num'] = SetAccountFlow::where($ali)->count();
        $list['ali']['ali_money'] = array_sum(SetAccountFlow::where($ali)->column('in_amount'));
        $arr1_ali = SetAccountFlow::where($ali_yes)->count();
        $r_ali1 = $this->yunsuan($list['ali']['ali_num'],$arr1_ali);
        $list['ali']['ali_num'] = empty($list['ali']['ali_num']) ? ['ali_num' => 0] : ['ali_num' => $list['ali']['ali_num']];
        if($r_ali1 >= 0){
            $list['ali']['ali_num']['bill_num'] = $r_ali1;
            $list['ali']['ali_num']['lower'] = true;
        }else{
            $list['ali']['ali_num']['bill_num'] = abs($r_ali1);
            $list['ali']['ali_num']['lower'] = false;
        }
        $arr2_ali = array_sum(SetAccountFlow::where($ali_yes)->column('in_amount'));
        $r_ali2 = $this->yunsuan($list['ali']['ali_money'],$arr2_ali);
        $list['ali']['ali_money'] = empty($list['ali']['ali_money']) ? ['ali_money' => 0] : ['ali_money' => $list['ali']['ali_money']];
        if($r_ali2 >= 0){
            $list['ali']['ali_money']['bill_money'] = $r_ali2;
            $list['ali']['ali_money']['lower'] = true;
        }else{
            $list['ali']['ali_money']['bill_money'] = abs($r_ali2);
            $list['ali']['ali_money']['lower'] = false;
        }
        //银行卡 条件
        $blank = [
            ['payment_mode','=','银行卡'],
            ['business_time','between',[$start_time,$end_time]],
            ['business_type','=','销售单']
        ];
        $list['blank']['blank_num'] = SetAccountFlow::where($blank)->count();
        $list['blank']['blank_money'] = array_sum(SetAccountFlow::where($blank)->column('in_amount'));
        $arr1_blank = SetAccountFlow::where($blank_yes)->count();
        $r_blank1 = $this->yunsuan($list['blank']['blank_num'],$arr1_blank);
        $list['blank']['blank_num'] = empty($list['blank']['blank_num']) ? ['blank_num' => 0] : ['blank_num' => $list['blank']['blank_num']];
        if($r_blank1 >= 0){
            $list['blank']['blank_num']['bill_num'] = $r_blank1;
            $list['blank']['blank_num']['lower'] = true;
        }else{
            $list['blank']['blank_num']['bill_num'] = abs($r_blank1);
            $list['blank']['blank_num']['lower'] = false;
        }
        $arr2_blank = array_sum(SetAccountFlow::where($blank_yes)->column('in_amount'));
        $r_blank2 = $this->yunsuan($list['blank']['blank_money'],$arr2_blank);
        $list['blank']['blank_money'] = empty($list['blank']['blank_money']) ? ['blank_money' => 0] : ['blank_money' => $list['blank']['blank_money']];
        if($r_blank2 >= 0){
            $list['blank']['blank_money']['bill_money'] = $r_blank2;
            $list['blank']['blank_money']['lower'] = true;
        }else{
            $list['blank']['blank_money']['bill_money'] = abs($r_blank2);
            $list['blank']['blank_money']['lower'] = false;
        }
        $yesterday[] = ['status','=',4];
        $list2 = SaleModel::where($yesterday)->field('id,payment')->cache(self::cache_time)->select();
        $yesterday_sale_money = [];
        $yesterday_sale_num = [];
        foreach ($list2 as $k=>$v){
            $yesterday_sale_num[] = $v['id'];
            $yesterday_sale_money[] = $v['payment'];
        }
        $total_money = $this->yunsuan($list['sale_money'],array_sum($yesterday_sale_money));
        $list['sale_money'] = empty($list['sale_money']) ? ['sale_money' =>0] : ['sale_money' =>$list['sale_money']];
        if($total_money >= 0){
            $list['sale_money']['bill_sale_money'] = !empty($total_money) ? abs($total_money) : 0;
            $list['sale_money']['lower'] = true;
        }else{
            $list['sale_money']['bill_sale_money'] = !empty($total_money) ? abs($total_money) : 0;
            $list['sale_money']['lower'] = false;
        }
        $total_num = $this->yunsuan($list['sale_num'],count($yesterday_sale_num));
        $list['sale_num'] = empty($list['sale_num']) ? ['sale_num' => 0] : ['sale_num' => $list['sale_num']];
        if($total_num >= 0){
            $list['sale_num']['bill_sale_num'] = $total_num;
            $list['sale_num']['lower'] = true;
        }else{
            $list['sale_num']['bill_sale_num'] = abs($total_num);
            $list['sale_num']['lower'] = false;
        }
        $list3 = SaleReturn::where($yesterday)->field('id,payment')->cache(self::cache_time)->select();
        $yesterday_return_money = [];
        $yesterday_return_num = [];
        foreach ($list3 as $k=>$v){
            $yesterday_return_num[] = $v['id'];
            $yesterday_return_money[] = $v['payment'];
        }
        $return_money = $this->yunsuan($list['return_money'],array_sum($yesterday_return_money));
        $list['return_money'] = empty($list['return_money']) ? ['return_money' => 0] : ['return_money' => $list['return_money']];
        if($return_money >= 0){
            $list['return_money']['bill_return_money'] = $return_money;
            $list['return_money']['lower'] = true;
        }else{
            $list['return_money']['bill_return_money'] = abs($return_money);
            $list['return_money']['lower'] = false;
        }
        $return_num = $this->yunsuan($list['return_num'],count($yesterday_return_num));
        $list['return_num'] = empty($list['return_num']) ? ['return_num' => 0] : ['return_num' => $list['return_num']];
        if($return_num >= 0){
            $list['return_num']['bill_return_num'] = $return_num;
            $list['return_num']['lower'] = true;
        }else{
            $list['return_num']['bill_return_num'] = abs($return_num);
            $list['return_num']['lower'] = false;
        }
        // var_dump(array_filter($list, function($v) {
        //     return is_array($v);
        // }));exit();
        $list['sum'] = [
            'sum_money' => [
                'bill_money' => array_sum([
                    $list['xian']['xian_money']['bill_money'],
                    $list['weChat']['weChat_money']['bill_money'],
                    $list['ali']['ali_money']['bill_money'],
                    $list['blank']['blank_money']['bill_money']]
                ),
                'lower' =>  array_sum([
                    $list['xian']['xian_money']['bill_money'] * ($list['xian']['xian_money']['lower'] ? -1 : 1),
                    $list['weChat']['weChat_money']['bill_money'] * ($list['weChat']['weChat_money']['lower'] ? -1 : 1),
                    $list['ali']['ali_money']['bill_money'] * ($list['ali']['ali_money']['lower'] ? -1 : 1),
                    $list['blank']['blank_money']['bill_money'] * ($list['blank']['blank_money']['lower'] ? -1 : 1),
                ])  > 0 ? true :false,
                'sum_money' => array_sum([
                    $list['xian']['xian_money']['xian_money'],
                    $list['weChat']['weChat_money']['weChat_money'],
                    $list['ali']['ali_money']['ali_money'],
                    $list['blank']['blank_money']['blank_money'],])
                ],
            'sum_num' => [
                'bill_num' => array_sum([
                    $list['xian']['xian_num']['bill_num'],
                    $list['weChat']['weChat_num']['bill_num'],
                    $list['ali']['ali_num']['bill_num'],
                    $list['blank']['blank_num']['bill_num']]
                ),
                'lower' => array_sum([
                    $list['xian']['xian_num']['bill_num'] * ($list['xian']['xian_num']['lower'] ? -1 : 1),
                    $list['weChat']['weChat_num']['bill_num'] * ($list['weChat']['weChat_num']['lower'] ? -1 : 1),
                    $list['ali']['ali_num']['bill_num'] * ($list['ali']['ali_num']['lower'] ? -1 : 1),
                    $list['blank']['blank_num']['bill_num'] * ($list['blank']['blank_num']['lower'] ? -1 : 1),
                ]) > 0 ? true :false,
                'sum_num' => array_sum([
                    $list['xian']['xian_num']['xian_num'],
                    $list['weChat']['weChat_num']['weChat_num'],
                    $list['ali']['ali_num']['ali_num'],
                    $list['blank']['blank_num']['blank_num'],])
                ],
            ];




        // var_dump(array_map(function($v) {
        //     var_dump($v);
        //     var_dump('--------------------------------------------------');
        // }, array_filter($list, function($v) {
        //     return is_array($v);
        // })));exit();
        return $this->returnJson(200,'success',$list);
    }

    /**
     * 经营概况 ----- 客户分析
     */
    public function customerAnal(Request $request)
    {
        $data = $request->param();
        $where = [];
        if(!empty($data['start_time']) && !empty($data['end_time'])){
            $where[] = ['create_time','between',[strtotime($data['start_time']),strtotime($data['end_time'])]];
        }
        $where[] = ['status','=',4];
        $list1 = SaleModel::where($where)->field('id,kid,payment')->order('id desc')->cache(self::cache_time)->select();
        $money = [];
        $num = [];
        foreach ($list1 as $k=>$v){
            $nums = array_sum(SaleRelation::where('pid',$v['id'])->column('put_number'));
            $list1[$k]['num'] = $nums;
            $money[] = $v['payment'];
            $num[] = $nums;
        }
        $list = [];
        foreach ($list1 as $k=>$v){
            if(!isset($list[$v['kid']])){
                $list[$v['kid']] = $v;
                $list[$v['kid']]['kid'] = UserModel::where('id',$v['kid'])->value('name');
            }else{
                $list[$v['kid']]['num'] += $v['num'];
                $list[$v['kid']]['payment'] += $v['payment'];
            }
        }
        $list =$this->arrayPaginate($list, $data['page'], $data['size'])->toArray();
        $list['money'] =array_sum($money);
        $list['num'] =array_sum($num);
        //昨天总金额、总数量
        $where1[] = ['create_time','between',[strtotime($data['start_time']) - 86400,strtotime($data['end_time']) - 86400]];
        $where1[] = ['status','=',4];
        $list2 = SaleModel::where($where1)->field('id,payment')->order('id desc')->cache(self::cache_time)->select();
        $money1 = [];
        $num1 = [];
        foreach ($list2 as $k=>$v){
            $nums1 = array_sum(SaleRelation::where('pid',$v['id'])->column('put_number'));
            $money1[] = $v['payment'];
            $num1[] = $nums1;
        }
        $billMoney = $this->yunsuan($list['money'],array_sum($money1));
        $list['money'] = empty($list['money']) ? ['money' => 0] : ['money' => $list['money']];
        if($billMoney >= 0){
            $list['money']['bill_money'] = abs($billMoney);
            $list['money']['lower'] = true;
        }else{
            $list['money']['bill_money'] = abs($billMoney);
            $list['money']['lower'] = false;
        }
        $billNum = $this->yunsuan($list['num'],array_sum($num1));
        $list['num'] = empty($list['num']) ? ['num' => 0] : ['num' => $list['num']];
        if($billNum >= 0){
            $list['num']['bill_num'] = abs($billNum);
            $list['num']['lower'] = true;
        }else{
            $list['num']['bill_num'] = abs($billNum);
            $list['num']['lower'] = false;
        }
        return $this->returnJson(200,'success',$list);
    }

    public function yunsuan($data1,$data2)
    {
        //计算公式=100%*（14年销售额-13年销售额）/13年销售额;
        if($data1 == 0 || $data2 == 0 || $data1 == $data2){
            return 0;
        }
        return (($data1 - $data2) / $data2) * 1;
    }

    /**
     * 经营概况 ----- 商品分析
     */
    public function goodsAnal(Request $request)
    {
        $data = $request->param();
        $where = [];
        if(!empty($data['start_time']) && !empty($data['end_time'])){
            $where[] = ['create_time','between',[strtotime($data['start_time']),strtotime($data['end_time'])]];
        }
        if(!empty($data['store'])){
            $arr = Admin::where(['level'=>3,'store'=>$data['store']])->fetchCollection()->column('id');
            $where[] = ['sales','in',$arr];
        }
        $where[] = ['status','=',4];
        $arr = SaleModel::where($where)->field('id,payment')->order('id desc')->cache(self::cache_time)->select();
        $money = [];
        $num = [];
        $list1 = [];
        $pid = [];
        foreach($arr as $k=>$v){
            $pid[] = $v['id'];
        }
        $rel = SaleRelation::whereIn('pid',$pid)->select()->toArray();
        foreach ($rel as $k1=>$v1){
            $goods_id = Product::where('id',$v1['product_id'])->value('commodity_id');
            $goods = Commodity::where('id',$goods_id)->field('name,brand,unit')->find();
            $list1[$k1]['commodity_id'] = $goods_id;
            $list1[$k1]['name'] = $goods['name'];
            $list1[$k1]['brand'] = $goods['brand'];
            $list1[$k1]['unit'] = $goods['unit'];
            $list1[$k1]['num'] = $v1['put_number'];
            $list1[$k1]['money'] = $v1['discount_money'];
            $money[] = $v1['discount_money'];
            $num[] = $v1['put_number'];
        }
        $list = [];
        foreach ($list1 as $k=>$v){
            if(!isset($list[$v['commodity_id']])){
                $list[$v['commodity_id']] = $v;
            }else{
                /*$list[$k]['commodity_id'] = $v['commodity_id'];
                $list[$k]['name'] = $v['name'];
                $list[$k]['brand'] = $v['brand'];
                $list[$k]['unit'] = $v['unit'];*/
                //print_r($list[$k]);die;
                $list[$v['commodity_id']]['num'] += $v['num'];
                $list[$v['commodity_id']]['money'] += $v['money'];
            }
        }
        $list =$this->arrayPaginate($list, $data['page'], $data['size'])->toArray();
        $list['num'] = array_sum($num);
        $list['money'] = array_sum($money);
        //昨天总金额、总数量
        $where1[] = ['create_time','between',[strtotime($data['start_time']) - 86400,strtotime($data['end_time']) - 86400]];
        $where1[] = ['status','=',4];
        $list2 = SaleModel::where($where1)->field('id,payment')->order('id desc')->cache(self::cache_time)->select();
        $money1 = [];
        $num1 = [];
        foreach ($list2 as $k=>$v){
            $nums1 = array_sum(SaleRelation::where('pid',$v['id'])->column('put_number'));
            $money1[] = $v['payment'];
            $num1[] = $nums1;
        }
        $billMoney = $this->yunsuan($list['money'],array_sum($money1));
        $list['money'] = empty($list['money']) ? ['money' => 0] : ['money' => $list['money']];
        if($billMoney >= 0){
            $list['money']['bill_money'] = abs($billMoney);
            $list['money']['lower'] = true;
        }else{
            $list['money']['bill_money'] = abs($billMoney);
            $list['money']['lower'] = false;
        }
        $billNum = $this->yunsuan($list['num'],array_sum($num1));
        $list['num'] = empty($list['num']) ? ['num' => 0] : ['num' => $list['num']];
        if($billNum >= 0){
            $list['num']['bill_num'] = abs($billNum);
            $list['num']['lower'] = true;
        }else{
            $list['num']['bill_num'] = abs($billNum);
            $list['num']['lower'] = false;
        }
        return $this->returnJson(200,'success',$list);
    }

    /**
     * 经营概况 ----- 店员分析
     */
    public function clerkAnal(Request $request)
    {
        $data = $request->param();
        $where = [];
        if(!empty($data['start_time']) && !empty($data['end_time'])){
            $where[] = ['create_time','between',[strtotime($data['start_time']),strtotime($data['end_time'])]];
        }
        if(!empty($data['store'])){
            $arr = Admin::where(['level'=>3,'store'=>$data['store']])->fetchCollection()->column('id');
            $where[] = ['sales','in',$arr];
        }
        $where[] = ['status','=',4];
        $arr1 = SaleModel::where($where)->field('id,sales,payment')->order('id desc')->cache(self::cache_time)->select();
        $money = [];
        $list = [];
        foreach ($arr1 as $k=>$v){
            $money[] = $v['payment'];
            if(!isset($list[$v['sales']])){
                $list[$v['sales']] = $v;
                $list[$v['sales']]['num'] = SaleModel::where(['sales'=>$v['sales'],'status'=>4])->count();
                $list[$v['sales']]['sales'] = Admin::where('id',$v['sales'])->value('name');
            }else{
                $list[$v['sales']]['payment'] += $v['payment'];
                $list[$v['sales']]['num'] = SaleModel::where(['sales'=>$v['sales'],'status'=>4])->count();
                $list[$v['sales']]['sales'] = Admin::where('id',$v['sales'])->value('name');
            }
        }
        foreach ($list as $k=>$v){
            $list[$k]['price'] = array_sum($money) / count($arr1);
        }
        $list =$this->arrayPaginate($list, $data['page'], $data['size'])->toArray();
        $list['money'] = array_sum($money);
        $list['num'] = count($arr1);
        //昨天总金额、总数量
        $where1[] = ['create_time','between',[strtotime($data['start_time']) - 86400,strtotime($data['end_time']) - 86400]];
        $where1[] = ['status','=',4];
        $list2 = SaleModel::where($where1)->field('id,payment')->order('id desc')->cache(self::cache_time)->select();
        $money1 = [];
        $num1 = [];
        foreach ($list2 as $k=>$v){
            $nums1 = array_sum(SaleRelation::where('pid',$v['id'])->column('put_number'));
            $money1[] = $v['payment'];
            $num1[] = $nums1;
        }
        $billMoney = $this->yunsuan($list['money'],array_sum($money1));
        $list['money'] = empty($list['money']) ? ['money' => 0] : ['money' => $list['money']];
        if($billMoney >= 0){
            $list['money']['bill_money'] = abs($billMoney);
            $list['money']['lower'] = true;
        }else{
            $list['money']['bill_money'] = abs($billMoney);
            $list['money']['lower'] = false;
        }
        $billNum = $this->yunsuan($list['num'],array_sum($num1));
        $list['num'] = empty($list['num']) ? ['num' => 0] : ['num' => $list['num']];
        if($billNum >= 0){
            $list['num']['bill_num'] = abs($billNum);
            $list['num']['lower'] = true;
        }else{
            $list['num']['bill_num'] = abs($billNum);
            $list['num']['lower'] = false;
        }
        return $this->returnJson(200,'success',$list);
    }

    /**
     * 经营概况 ----- 商品利润
     */
    public function goodsProfit(Request $request)
    {
        $data = $request->param();
	$arr = SaleModel::where('status',4)->field('id,small,payment')->cache(self::cache_time)->select();
	$pid = [];
        $small = [];
        $money = [];
        foreach($arr as $k=>$v){
            $pid[] = $v['id'];
            $small[] = $v['small'];
            $money[] = $v['payment'];
        }
        $rel = SaleRelation::whereIn('pid',$pid)->select()->toArray();
        $list1 = [];
        $num = [];
        foreach ($rel as $k1=>$v1){
            $goods_id = Product::where('id',$v1['product_id'])->value('commodity_id');
            $goods = Commodity::where('id',$goods_id)->field('name,purchase_price')->find();
            $list1[$k1]['commodity_id'] = $goods_id;
            $list1[$k1]['name'] = $goods['name'];
            $list1[$k1]['num'] = $v1['put_number'];
            $list1[$k1]['pur_price'] = $v1['put_number'] * $goods['purchase_price'];
            $num[] = $v1['put_number'];
        }
        $list = [];
        foreach ($list1 as $k=>$v){
            if(!isset($list[$v['commodity_id']])){
                $list[$v['commodity_id']] = $v;
            }else{
                $list[$v['commodity_id']]['num'] += $v['num'];
                $list[$v['commodity_id']]['pur_price'] += $v['pur_price'];
            }
        }
        $cost = [];
        $profit = [];
        foreach ($list as $k=>$v){
            $trade_price = Commodity::where('id',$v['commodity_id'])->value('trade_price');
            $avg = $v['pur_price'] / array_sum($num);
            $list[$k]['cost'] = $avg * $v['num'];
            $list[$k]['profit'] = $trade_price * $v['num'] - $list[$k]['cost'];
            $cost[] = $list[$k]['cost'];
            $profit[] = $list[$k]['profit'];
        }
        $list =$this->arrayPaginate($list, $data['page'], $data['size'])->toArray();
        $list['small'] = array_sum($small);
        $list['money'] = array_sum($money);
        $list['cost'] = array_sum($cost);
        $list['profit'] = array_sum($profit);
        return $this->returnJson(200,'success',$list);
    }

    /**
     * 经营概况 ----- 门店利润
     */
    public function storeProfit(Request $request)
    {
        $data = $request->param();
        $arr1 = SaleModel::where('status',4)->field('id,sales,small,payment')->cache(self::cache_time)->select();
        $money = [];
        $small = [];
        $pid = [];
        $arr = [];
        foreach ($arr1 as $k=>$v){
            $money[] = $v['payment'];
            $small[] = $v['small'];
            $pid[] = $v['id'];
            $store = Admin::where('id',$v['sales'])->value('store');
            $arr[] = [
                'id' => $v['id'],
                'store_id' => $store,
                'store_name' => StoreModel::where('id',$store)->value('name')
            ];
        }
        $rel = SaleRelation::whereIn('pid',$pid)->select()->toArray();
        $num = [];
        foreach ($rel as $k1=>$v1){
            foreach ($arr as $k2=>$v2) {
                if (in_array($v1['pid'], $pid)) {
                    $goods_id = Product::where('id', $v1['product_id'])->value('commodity_id');
                    $goods = Commodity::where('id', $goods_id)->field('name,purchase_price')->find();
                    $arr[$k2]['commodity_id'] = $goods_id;
                    $arr[$k2]['num'] = $v1['put_number'];
                    $num[] = $v1['put_number'];
                    $arr[$k2]['pur_price'] = $v1['put_number'] * $goods['purchase_price'];
                }
            }
        }
        $list = [];
        foreach ($arr as $k=>$v){
            if(!isset($list[$v['store_id']])){
                $list[$v['store_id']] = $v;
            }else{
                $list[$v['store_id']]['num'] += $v['num'];
                $list[$v['store_id']]['pur_price'] += $v['pur_price'];
            }
        }
        $cost = [];
        $profit = [];
        foreach ($list as $k=>$v){
            $trade_price = Commodity::where('id',$v['commodity_id'])->value('trade_price');
            $avg = $v['pur_price'] / array_sum($num);
            $list[$k]['cost'] = $avg * $v['num'];
            $list[$k]['profit'] = $trade_price * $v['num'] - $list[$k]['cost'];
            $cost[] = $list[$k]['cost'];
            $profit[] = $list[$k]['profit'];
        }
        $list =$this->arrayPaginate($list, $data['page'], $data['size'])->toArray();
        $list['small'] = array_sum($small);
        $list['money'] = array_sum($money);
        $list['cost'] = array_sum($cost);
        $list['profit'] = array_sum($profit);
        return $this->returnJson(200,'success',$list);
    }
}
